package com.fengxg.test.recursive.task;

import com.fengxg.test.recursive.dto.TaskResultDTO;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.RecursiveTask;

/**
 * @Desccription 分片后执行业务任务的具体类
 * @auther Fengxg
 * @create 2018/7/25
 */
public class TaskWorkTask extends RecursiveTask<TaskResultDTO>{

    public TaskWorkTask(int startIndex, int endIndex, CountDownLatch countDownLatch, String[] datas, int workNum) {
        super();
        this.startIndex = startIndex;
        this.endIndex = endIndex;
        this.datas = datas;
        this.workNum = workNum;
        this.countDownLatch = countDownLatch;
    }

    private int workNum;
    private int startIndex;
    private int endIndex;
    private CountDownLatch countDownLatch;
    private String[] datas;

    @Override
    protected TaskResultDTO compute() {
        TaskResultDTO taskResultDTO = new TaskResultDTO();
        Long errorCount = 0L;
        Long successCount = 0L;
        Long totalCount = 0L;
        taskResultDTO.setErrorCount(errorCount);
        taskResultDTO.setSuccessCount(successCount);
        taskResultDTO.setTotalCount(totalCount);
        Thread t = Thread.currentThread();
        for (int i = startIndex; i < endIndex; i++) {
            try {
                Thread.sleep(100L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("workNum" + workNum  +"，第" + datas[i] + "任务," + "执行线程:" + t.getName());
            
            if (0 == i%3) {
                taskResultDTO.setErrorCount(taskResultDTO.getErrorCount() + 1);
            } else {
                taskResultDTO.setSuccessCount(taskResultDTO.getSuccessCount() + 1);
            }

            taskResultDTO.setTotalCount(taskResultDTO.getTotalCount() + 1);
        }
        countDownLatch.countDown();
        return taskResultDTO;
    }

    public int getStartIndex() {
        return startIndex;
    }

    public void setStartIndex(int startIndex) {
        this.startIndex = startIndex;
    }

    public int getEndIndex() {
        return endIndex;
    }

    public void setEndIndex(int endIndex) {
        this.endIndex = endIndex;
    }

    public String[] getDatas() {
        return datas;
    }

    public void setDatas(String[] datas) {
        this.datas = datas;
    }
}
